package com.agriculture.service.impl;

import com.agriculture.domain.Order;
import com.agriculture.domain.OrderItem;
import com.agriculture.domain.User;
import com.agriculture.domain.Product;
import com.agriculture.dto.InventoryProductDTO;
import com.agriculture.dto.Order.OrderDTO;
import com.agriculture.mapper.OrderItemMapper;
import com.agriculture.mapper.OrderMapper;
import com.agriculture.mapper.ProductMapper;
import com.agriculture.mapper.UserMapper;
import com.agriculture.service.DealerService;
import com.agriculture.exception.BusinessException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DealerServiceImpl implements DealerService {

    @Autowired
    private ProductMapper productMapper;
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public List<Product> getPurchaseProducts(String search, String category, String supplier,
                                           BigDecimal minPrice, BigDecimal maxPrice,
                                           String sortBy, String sortOrder) {
        try {
            List<Product> products = productMapper.selectPurchaseProducts(search, category, supplier, 
                                                                        minPrice, maxPrice, sortBy, sortOrder);
            
            // 对每个产品进行数据转换和补充
            return products.stream().map(product -> {
                // 确保所有必要字段都有值
                if (product.getProductName() == null) {
                    product.setProductName("");
                }
                if (product.getCategory() == null) {
                    product.setCategory("");
                }
                if (product.getOwnerName() == null) {
                    product.setOwnerName("");
                }
                if (product.getUnit() == null) {
                    product.setUnit("件");
                }
                if (product.getPrice() == null) {
                    product.setPrice(BigDecimal.ZERO);
                }
                if (product.getStock() == null) {
                    product.setStock(0);
                }
                if (product.getType() == null) {
                    product.setType("agricultural");
                }
                if (product.getStatus() == null) {
                    product.setStatus("on_sale");
                }
                
                return product;
            }).collect(Collectors.toList());
            
        } catch (Exception e) {
            throw new BusinessException("获取农产品列表失败: " + e.getMessage());
        }
    }

    @Override
    public Product getProductDetail(Long id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order createOrder(OrderDTO orderDTO) throws Exception {
        // 检查商品是否存在
        Product product = productMapper.selectByPrimaryKey(orderDTO.getProductId());
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        
        // 检查库存
        if (product.getStock() < orderDTO.getQuantity()) {
            throw new BusinessException("商品库存不足");
        }
        
        // 创建订单
        Order order = new Order();
        BeanUtils.copyProperties(orderDTO, order);
        order.setOrderType(orderDTO.getOrderType()); // 设置订单类型
        order.setStatus(orderDTO.getStatus()); // 设置初始状态为 pending_review
        order.setCreatedAt(new Date());
        order.setTotalAmount(product.getPrice().multiply(new BigDecimal(orderDTO.getQuantity())));
        order.setBuyerId(orderDTO.getBuyerId()); // 确保设置买方ID
        order.setSellerId(product.getOwnerId()); // 设置卖方ID（通过product获取）
        order.setNotes(orderDTO.getRemark()); // 设置备注
        order.setShippingAddress(orderDTO.getDeliveryAddress()); // 设置配送地址

        // 获取买方名称
        User buyer = userMapper.selectById(orderDTO.getBuyerId());
        if (buyer != null) {
            order.setBuyerName(buyer.getUsername()); // 设置买方名称
        } else {
            throw new BusinessException("买方不存在");
        }

        // 保存订单
        orderMapper.insert(order); // 确保使用正确的mapper

        // 创建订单项
        OrderItem orderItem = new OrderItem();
        orderItem.setProductId(orderDTO.getProductId());
        orderItem.setQuantity(orderDTO.getQuantity());
        orderItem.setUnitPrice(product.getPrice());
        orderItem.setOrderId(order.getOrderId()); // 设置订单ID
        orderItemMapper.insert(orderItem); // 插入订单项

        // 扣减库存
        product.setStock(product.getStock() - orderDTO.getQuantity());
        productMapper.update(product);

        return order;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelPurchaseOrder(Long id, String reason) throws Exception {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 检查订单状态
        if (!"待审核".equals(order.getStatus()) && !"待接单".equals(order.getStatus())) {
            throw new BusinessException("当前订单状态不可取消");
        }
        
        // 更新订单状态
        order.setStatus("已取消");
        order.setCancelReason(reason);
        order.setCancelTime(new Date());
        orderMapper.updateById(order);
        
        // 恢复库存
        for (OrderItem item : order.getOrderItems()) {
            Product product = productMapper.selectByPrimaryKey(item.getProductId());
            product.setStock(product.getStock() + item.getQuantity());
            productMapper.update(product);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirmReceipt(Long id) throws Exception {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 检查订单状态
        if (!"待收货".equals(order.getStatus())) {
            throw new BusinessException("当前订单状态不可确认收货");
        }
        
        // 更新订单状态
        order.setStatus("待付款");
        order.setReceiptTime(new Date());
        orderMapper.updateById(order);
    }
    
    /**
     * 生成订单编号
     */
    private String generateOrderNo() {
        return "PO" + System.currentTimeMillis();
    }

    @Override
    public List<User> listDealers() {
        // 查询 role 为 dealer 的用户
        return userMapper.selectByRole("dealer");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Product createProduct(Long dealerId, Product product) {
        // 验证库存商品是否存在
        Product stockProduct = productMapper.findById(product.getProductId());
        if (stockProduct == null) {
            throw new BusinessException("库存商品不存在");
        }

        // 设置商品基本信息
        product.setProductName(stockProduct.getProductName());
        product.setType("processed"); // 经销商商品类型为processed
        product.setCategory(stockProduct.getCategory());
        product.setUnit(stockProduct.getUnit());
        product.setOwnerId(dealerId);
        product.setOwnerType("dealer");
        product.setStatus("on_sale");
        product.setCreatedAt(new Date());
        product.setUpdateTime(new Date());

        // 验证库存
        if (product.getStock() == null || product.getStock() <= 0) {
            throw new BusinessException("库存数量必须大于0");
        }

        // 验证价格
        if (product.getPrice() == null || product.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException("价格必须大于0");
        }

        // 保存商品
        productMapper.insert(product);
        return product;
    }

    @Override
    public void updateProductStatus(Long productId, String status) {
        Product product = productMapper.selectByPrimaryKey(productId);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        
        // 验证商品所有权
        if (!"dealer".equals(product.getOwnerType())) {
            throw new BusinessException("无权操作此商品");
        }
        
        product.setStatus(status);
        product.setUpdateTime(new Date());
        productMapper.update(product);
    }

    @Override
    public void deleteProduct(Long dealerId, Long productId) {
        Product product = productMapper.findById(productId);
        if (product == null) {
            throw new BusinessException("商品不存在");
        }
        
        // 验证商品所有权
        if (!dealerId.equals(product.getOwnerId()) || !"dealer".equals(product.getOwnerType())) {
            throw new BusinessException("无权删除此商品");
        }
        
        // 只能删除已下架的商品
        if (!"off_shelf".equals(product.getStatus())) {
            throw new BusinessException("只能删除已下架的商品");
        }
        
        productMapper.delete(productId);
    }

    @Override
    public List<Product> getProducts(Long dealerId, String search, int page, int pageSize) {
        return productMapper.getProductsByPage(
            dealerId,
            "dealer",
            search,
            null,
            (page - 1) * pageSize,
            pageSize
        );
    }

    @Override
    public List<InventoryProductDTO> getInventoryProducts(String search, String category,
                                                         Long userId, int page, int pageSize) {
        try {
            return productMapper.selectInventoryProducts(
                search,
                category,
                userId,
                (page - 1) * pageSize,
                pageSize
            );
        } catch (Exception e) {
            throw new BusinessException("获取库存商品列表失败: " + e.getMessage());
        }
    }
}
